package org.example.dom4j;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class Jxl2Dom4j {

    public static void main(String[] args) {

        try {
            xls2Xml("C:\\Users\\hp\\IdeaProjects\\demo1\\untitled1\\output.xls",
                   "C:\\Users\\hp\\Desktop\\values\\values-ja\\strings.xml",
                    0,"ja","C:\\Users\\hp\\IdeaProjects\\demo1\\untitled1\\output.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (BiffException e) {
            throw new RuntimeException(e);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
//        try {
//            lang2langCopy(
//                    "C:\\Users\\hp\\Desktop\\ECTRi language list Android version (1)-updated,fi.xls",
//                    "English",
//                    "Finnish",
//                    "C:\\Users\\hp\\Desktop\\strings.xml"
//            );
//        } catch (IOException | BiffException | DocumentException e) {
//            throw new RuntimeException(e);
//        }

//        try {
//            dom2domFill("C:\\Users\\hp\\Desktop\\strings-fi.xml",
//                    "C:\\Users\\hp\\IdeaProjects\\demo1\\untitled1\\target.xml");
//        } catch (DocumentException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

    /**
     * xls转xml
     * @param translationXlsPath 已经翻译的xls表格
     * @param xml 翻译语言的对应的xml文件
     * @param titleRow lang 出现在的第几行
     * @param witchLang 转换的是哪个语言
     * @param outputFilePath 结果输出位置
     * @throws IOException
     * @throws BiffException
     * @throws DocumentException
     */
    private static void xls2Xml(String translationXlsPath,String xml,int titleRow,String witchLang,String outputFilePath) throws IOException, BiffException, DocumentException {
        File excel = new File(translationXlsPath);
        FileInputStream fileInputStream = new FileInputStream(excel.getAbsoluteFile());
        WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding("ISO-8859-1");
        Workbook workbook = Workbook.getWorkbook(fileInputStream,workbookSettings);
        Sheet sheet = workbook.getSheet(0);
        Cell[] titleRowCell = sheet.getRow(titleRow);
        int keyColum = 0;
        int witchLangColum = 0;
        for (int i = 0; i < titleRowCell.length; i++) {
            if (titleRowCell[i].getContents().equals(witchLang)){
                witchLangColum = i;
                break;
            }
        }
        Cell[] keyColumCells = sheet.getColumn(keyColum);
        HashMap<String,String> excelData = new HashMap<>();
        for (int i = 0; i < keyColumCells.length; i++) {
            excelData.put(keyColumCells[i].getContents(),sheet.getCell(witchLangColum,keyColumCells[i].getRow()).getContents());
        }
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(new File(xml));
        Element rootElement = read.getRootElement();
        List<Element> elements = rootElement.elements("string");
        for (int i = 0; i < elements.size(); i++) {
            Element element = elements.get(i);
            Attribute name = element.attribute("name");
            String text = excelData.get(name.getValue());
            if (text == null) continue;
            element.setText(text);
        }
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(outputFilePath));
        xmlWriter.write(read);
        xmlWriter.close();
    }

    /**
     * 根据翻译文档的某一种语言对应原语言文档的文本，将翻译文本更新
     * @param translationFilePath
     * @param translationFileApplyItemTitle
     * @param translationFileTranslatedItemTitle
     * @param mirrorTranslationFilePath
     * @throws IOException
     * @throws BiffException
     * @throws DocumentException
     */
    private static void lang2langCopy(String translationFilePath,
                                      String translationFileApplyItemTitle,
                                      String translationFileTranslatedItemTitle,
                                      String mirrorTranslationFilePath) throws IOException, BiffException, DocumentException {
        //已经翻译的excel文件
        File excel = new File(translationFilePath);

        FileInputStream fileInputStream = new FileInputStream(excel.getAbsoluteFile());
        WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding("ISO-8859-1");
        Workbook workbook = Workbook.getWorkbook(fileInputStream,workbookSettings);
        Sheet sheet = workbook.getSheet(0);

        Cell[] row = sheet.getRow(0);

        int applyRow = -1;
        int translationRow = -1;
        for (int i = 0; i < row.length; i++) {
            String contents = row[i].getContents();
            if (contents.equals(translationFileApplyItemTitle)) {
                applyRow = i;
            }
            if (contents.equals(translationFileTranslatedItemTitle)) {
                translationRow = i;
            }
        }

        Cell[] allApplyData = sheet.getColumn(applyRow);
        Cell[] allTranslationData = sheet.getColumn(translationRow);
        assert allApplyData.length == allTranslationData.length;

        HashMap<String, String> translationMap = new HashMap<>();
        for (int i = 0; i < allApplyData.length; i++) {
            translationMap.put(allApplyData[i].getContents(), allTranslationData[i].getContents());
        }

        File targetXmlFile = new File(mirrorTranslationFilePath);
        Document read = new SAXReader().read(targetXmlFile);
        Element rootElement = read.getRootElement();
        for (Iterator it = rootElement.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            String translationData = translationMap.getOrDefault(element.getText(), "未找到翻译");
            element.setText(translationData);
        }
        XMLWriter writer = new XMLWriter(new FileWriter(new File("C:\\Users\\hp\\IdeaProjects\\demo1\\untitled1\\target.xml")));
        writer.write(read);
        writer.close();
    }

    /**
     * 将源文件与翻译文件对比，如翻译文件当中含有 未找到翻译 的选项，不进行替换内容；否则替换掉源文件当中的内容
     * @param sourceFilePath
     * @param translationPath
     * @throws DocumentException
     * @throws IOException
     */
    private static void dom2domFill(String sourceFilePath,String translationPath) throws DocumentException, IOException {
        File sourceFile = new File(sourceFilePath);
        File translationFile = new File(translationPath);

        HashMap<String, String> translationMap = new HashMap<>();
        Document translationDoc = new SAXReader().read(translationFile);
        Element rootElement1 = translationDoc.getRootElement();
        for (Iterator it = rootElement1.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            Attribute name = element.attribute("name");
            String text = element.getText();
            translationMap.put(name.getValue(),text);
        }

        Document read = new SAXReader().read(sourceFile);
        Element rootElement = read.getRootElement();
        for (Iterator it = rootElement.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            Attribute name = element.attribute("name");
            String translationRes = translationMap.getOrDefault(name.getValue(), "");
            if (translationRes.equals("未找到翻译") || translationRes.isEmpty()){
                continue;
            }else {
                element.setText(translationRes);
            }
        }

        XMLWriter writer = new XMLWriter(new FileWriter(new File("C:\\Users\\hp\\IdeaProjects\\demo1\\untitled1\\target.xml")));
        writer.write(read);
        writer.close();


    }
}
